package com.tanhua.app.interceptor;

import com.tanhua.app.controllerservice.UserService;
import com.tanhua.domain.db.User;
import com.tanhua.domain.vo.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override  //在controller的方法前做拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取token
        String token = request.getHeader("Authorization");
        if(token==null){
            response.setStatus(401); //权限不足
            return false;
        }
        // 根据token获取用户
        User user = userService.fromRedisUser(token);
        if(user==null){
            response.setStatus(401); //权限不足
            return false;
        }
        // 将用户放在threadLocal中
        UserHolder.saveUser(user);
        // 放行
        return true;
    }

    @Override //整个响应结束
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser(); //移除对象
    }
}
